<template>
  <el-dialog
    v-model="dialogVisible"
    class="shared-sign-dialog"
    :draggable="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="80%"
    @close="handleClose"
  >
    <template #header>
      <h3>{{ dialogTitle }}</h3>
    </template>
    <div class="contract-container">
      <!-- 患者查询区域 -->
      <div class="search-section" v-if="dialogType === 'add'">
        患者姓名:
        <el-input v-model="patientQuery" style="width: 200px;" placeholder="请输入" />
        <el-button style="margin-left: 10px;" type="primary" @click="searchPatient">查询</el-button>
      </div>

      <!-- 患者信息区域 -->
      <el-card class="patient-info-card" v-if="patientInfo.recordName">
        <div class="patient-info">
          <span style="font-weight: bold;">{{ patientInfo.recordName }}</span>
          <span style="color: gray;">{{ patientInfo.recordSex }} {{ patientInfo.recordAge }}岁</span>
          <span style="color: gray;">出生日期: {{ patientInfo.recordBirth }}</span>
          <span style="color: gray;">身份证号: {{ patientInfo.recordIdcard }}</span>
        </div>
      </el-card>

      <!-- 签约信息区域 -->
      <el-card class="sign-info-card">
        <el-form
          ref="ruleFormRef"
          style="max-width: 100%"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="签约团队">
                <el-select v-model="ruleForm.cSignTeam" placeholder="请选择签约团队" style="width: 300px;">
                  <el-option label="沙河社区家庭医生团队" value="沙河社区家庭医生团队"></el-option>
                  <!-- 可根据实际需求添加更多选项 -->
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="签约医生">
                <el-select v-model="ruleForm.cSignDoctor" placeholder="请选择主管医生" style="width: 300px;">
                  <el-option label="豆豆" value="豆豆"></el-option>
                  <!-- 可根据实际需求添加更多选项 -->
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="签约周期">
            <el-date-picker v-model="ruleForm.cSignBegin" type="date" placeholder="yyyy/mm/dd" />
            ~
            <el-date-picker v-model="ruleForm.cSignEnd" type="date" placeholder="yyyy/mm/dd" />
          </el-form-item>
          <el-form-item label="管理慢病">
            <el-select v-model="ruleForm.cSignManage" placeholder="请选择管理慢病" style="width: 300px;">
              <el-option label="原发性高血压" value="原发性高血压"></el-option>
              <el-option label="2型糖尿病" value="2型糖尿病"></el-option>
              <el-option label="慢阻肺" value="慢阻肺"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="管理级别">
            <el-select v-model="ruleForm.cSignLevel" placeholder="请选择管理级别" style="width: 300px;">
              <el-option label="一级" value="一级"></el-option>
              <el-option label="二级" value="二级"></el-option>
              <el-option label="三级" value="三级"></el-option>
              <!-- 可根据实际需求添加更多选项 -->
            </el-select>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 服务包区域 -->
      <el-card class="service-package-card">
        <el-table :data="servicePackages" border style="width: 100%">
          <el-table-column prop="checked" label="选择">
            <template #default="scope">
              <el-checkbox v-model="scope.row.checked"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="服务名称"></el-table-column>
          <el-table-column prop="fee" label="费用"></el-table-column>
          <el-table-column prop="operation" label="操作">
            <template #default="scope">
              <el-button type="text" @click="handleServiceOperation(scope.row)">服务项目</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 绑定设备区域 -->
      <el-card class="device-card">
        <el-table :data="devices" border style="width: 100%">
          <el-table-column prop="name" label="设备名称"></el-table-column>
          <el-table-column prop="sn" label="设备SN号"></el-table-column>
          <el-table-column prop="bindTime" label="绑定时间"></el-table-column>
          <el-table-column prop="status" label="状态"></el-table-column>
          <el-table-column prop="operation" label="操作">
            <template #default="scope">
              <el-button type="text" @click="handleDeviceUnbind(scope.row)">解绑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 签约凭证区域 -->
      <el-card class="voucher-card">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:5203/api/Images/img"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="ruleForm.cSignImage" :src="ruleForm.cSignImage" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="voucher-tip">说明：支持上传jpg、png、pdf文件格式，大小不超过3M。</div>
      </el-card>
    </div>

    <!-- 操作按钮区域 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, defineProps, defineEmits } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadProps } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import axios from 'axios';
import { Write } from '@/Http/Axios';

// 定义组件属性
interface Props {
  visible: boolean
  dialogType: 'add' | 'edit' | 'renew'
  patientData?: any // 调整模式下传递的患者数据
}


const props = defineProps<Props>()

// 对话框标题计算属性
const dialogTitle = computed(() => {
  if (props.dialogType === 'edit') {
    return '调整签约信息'
  } else if (props.dialogType === 'renew') {
    return '续签签约信息'
  } else {
    return '慢性病患者签约'
  }
})

// 定义事件发射
const emit = defineEmits(['update:visible', 'close', 'success'])

// 定义表单接口
interface RuleForm {
  cSignTeam: string;
  cSignDoctor: string;
  cSignBegin: string;
  cSignEnd: string;
  cSignManage: string;
  cSignLevel: string;
  cSignImage: string;
  recordId: number;
  cSignId: number;
}

// 对话框可见性计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => {
    emit('update:visible', val);
  }
})

// 监听props变化，根据模式初始化数据
watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 如果是调整模式，初始化表单数据
    if (props.dialogType === 'edit' && props.patientData) {
      ruleForm.cSignId = props.patientData.cSignId || 0
      ruleForm.cSignTeam = props.patientData.cSignTeam || ''
      ruleForm.cSignDoctor = props.patientData.cSignDoctor || ''
      ruleForm.cSignBegin = props.patientData.cSignBegin || ''
      ruleForm.cSignEnd = props.patientData.cSignEnd || ''
      ruleForm.cSignManage = props.patientData.cSignManage || ''
      ruleForm.cSignLevel = props.patientData.cSignLevel || ''
      ruleForm.cSignImage = props.patientData.cSignImage || ''
      ruleForm.recordId = props.patientData.recordId || 0
      
      // 初始化患者信息
      patientInfo.value = {
        recordName: props.patientData.recordName || '',
        recordSex: props.patientData.recordSex || '',
        recordAge: props.patientData.recordAge || '',
        recordBirth: props.patientData.recordBirth || '',
        recordIdcard: props.patientData.recordIdcard || ''
      }
    } else {
      // 新增模式清空表单和患者信息
      Object.assign(ruleForm, {
        cSignTeam: '',
        cSignDoctor: '',
        cSignBegin: '',
        cSignEnd: '',
        cSignManage: '',
        cSignLevel: '',
        cSignImage: '',
        recordId: 0
      })
      
      patientInfo.value = {
        recordName: '',
        recordSex: '',
        recordAge: '',
        recordBirth: '',
        recordIdcard: ''
      }
    }
  }
});

// 患者查询相关
const patientQuery = ref('');
const patientInfo = ref({
  recordName: '',
  recordSex: '',
  recordAge: '',
  recordBirth: '',
  recordIdcard: ''
});

// 表单相关
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  cSignId:0,
  cSignTeam: '',
  cSignDoctor: '',
  cSignBegin: '',
  cSignEnd: '',
  cSignManage: '',
  cSignLevel: '',
  cSignImage: '',
  recordId: 0
});

// 表单验证规则
const rules = reactive<FormRules<RuleForm>>({
  cSignTeam: [
    { required: true, message: '请选择签约团队', trigger: 'blur' },
  ],
  cSignDoctor: [
    { required: true, message: '请选择签约医生', trigger: 'blur' },
  ],
  cSignBegin: [
    { required: true, message: '请选择签约开始时间', trigger: 'blur' },
  ],
  cSignEnd: [
    { required: true, message: '请选择签约结束时间', trigger: 'blur' },
  ],
  cSignManage: [
    { required: true, message: '请选择管理慢病', trigger: 'blur' },
  ],
  cSignLevel: [
    { required: true, message: '请选择管理级别', trigger: 'blur' },
  ],
});

// 监听患者数据变化
watch(() => props.patientData, (newVal) => {
  if (newVal && Object.keys(newVal).length > 0) {
    // 更新患者信息
    patientInfo.value = {
      recordName: newVal.recordName || '',
      recordSex: newVal.recordSex || '',
      recordAge: newVal.recordAge || '',
      recordBirth: newVal.recordBirth || '',
      recordIdcard: newVal.recordIdcard || ''
    };
    
    // 更新表单数据
    ruleForm.cSignId = newVal.cSignId || 0;
    ruleForm.cSignTeam = newVal.cSignTeam || '';
    ruleForm.cSignDoctor = newVal.cSignDoctor || '';
    ruleForm.cSignBegin = newVal.cSignBegin || '';
    ruleForm.cSignEnd = newVal.cSignEnd || '';
    ruleForm.cSignManage = newVal.cSignManage || '';
    ruleForm.cSignLevel = newVal.cSignLevel || '';
    ruleForm.cSignImage = newVal.cSignImage || '';
    ruleForm.recordId = newVal.recordId;
  }
}, { immediate: true });

// 服务包列表
const servicePackages = reactive([
  { checked: true, name: '高血压常规管理包', fee: 0 },
  { checked: true, name: '高血压增值管理包', fee: 200.00 },
]);

// 设备列表
const devices = reactive([
  { name: '血压计', sn: 'N10023001', bindTime: '2025-10-23 10:10:12', status: '在绑' },
  { name: '血糖仪', sn: 'N10023002', bindTime: '2025-10-23 10:10:12', status: '在绑' },
]);

// 处理服务操作
const handleServiceOperation = (row: any) => {
  // 可在此处添加服务项目操作逻辑，如弹窗展示服务详情等
  console.log('服务项目操作：', row);
};

// 处理设备解绑
const handleDeviceUnbind = (row: any) => {
  ElMessageBox.confirm(
    `确认要解绑设备 ${row.name} 吗？`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then((res) => {

    // 实际项目中这里应该调用解绑API
    ElMessage.success('设备解绑成功');
  }).catch(() => {
    ElMessage.info('已取消解绑');
  });
};

// 处理图片上传成功
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  ruleForm.cSignImage = URL.createObjectURL(uploadFile.raw!);
};

// 处理图片上传前验证
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'application/pdf') {
    ElMessage.error('上传文件只能是 JPG、PNG 或 PDF 格式!');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 3) {
    ElMessage.error('上传文件大小不能超过 3MB!');
    return false;
  }
  return true;
};

// 查询患者
const searchPatient = () => {
  // 实际项目中这里应该调用查询患者API
  // 这里使用模拟数据
  if (patientQuery.value) {
    patientInfo.value = {
      recordName: patientQuery.value,
      recordSex: '男',
      recordAge: '65',
      recordBirth: '1959-01-01',
      recordIdcard: '110101195901011234'
    };
    ElMessage.success('查询成功');
  } else {
    ElMessage.warning('请输入患者姓名');
  }
};

// 关闭对话框
const handleClose = () => {
  emit('close');
};

// 取消操作
const handleCancel = () => {
  dialogVisible.value = false;
};

// 提交表单
const handleSubmit = async () => {
  if (!ruleFormRef.value) return;
  
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      // 根据对话框类型执行不同操作
      if (props.dialogType === 'edit') {
        // 编辑模式 - 更新签约信息
        updateSignInfo();
      } else if (props.dialogType === 'renew') {
        // 续签模式 - 续签签约信息
        renewSignInfo();
      } else {
        // 新增模式 - 创建签约
        createSign();
      }
    } else {
      console.log('表单验证失败:', fields);
    }
  });
};

// 更新签约信息
const updateSignInfo = () => {
  Write.put("http://localhost:5203/api/Managment/UpCSign", ruleForm).then(res => { 
    console.log('更新签约信息:', ruleForm.cSignId);
    ElMessage.success('签约信息更新成功');
    dialogVisible.value = false;
    emit('success');
  })
  // 实际项目中这里应该调用更新API
};

// 续签签约信息
const renewSignInfo = () => {
  // 实际项目中这里应该调用续签API
  console.log('续签签约信息:', ruleForm);
  ElMessage.success('续签成功');
  dialogVisible.value = false;
  emit('success');
};

// 创建签约
const createSign = () => {
  // 实际项目中这里应该调用创建API
  console.log('创建签约:', ruleForm);
  ElMessage.success('签约成功');
  dialogVisible.value = false;
  emit('success');
};
</script>

<style scoped>
.contract-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  position: relative;
}

.contract-container > * {
  position: relative;
  z-index: 1;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(120, 130, 140, 0.1);
}

.patient-info-card,
.sign-info-card,
.service-package-card,
.device-card,
.voucher-card {
  margin-bottom: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(120, 130, 140, 0.1);
  transition: all 0.3s ease;
}

.patient-info-card:hover,
.sign-info-card:hover,
.service-package-card:hover,
.device-card:hover,
.voucher-card:hover {
  box-shadow: 0 6px 25px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.patient-info-card {
  border-left: 5px solid #409eff;
}

.sign-info-card {
  border-left: 5px solid #67c23a;
}

.service-package-card {
  border-left: 5px solid #e6a23c;
}

.device-card {
  border-left: 5px solid #f56c6c;
}

.voucher-card {
  border-left: 5px solid #909399;
}

.patient-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.voucher-upload {
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  padding: 20px;
  border-radius: 0 0 12px 12px;
  margin: 0 -20px -20px -20px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
  border-radius: 10px;
}

/* 调整对话框遮罩层样式 */


.shared-sign-dialog :deep(.el-overlay-dialog) {
  /* 移除了透明背景设置 */
}

.shared-sign-dialog :deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
}

.shared-sign-dialog :deep(.el-dialog__header) {
  /* 移除了渐变背景 */
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
  padding: 20px;
}

.shared-sign-dialog :deep(.el-dialog__header .el-dialog__title) {
  font-weight: 600;
  font-size: 18px;
}

.shared-sign-dialog :deep(.el-button--primary) {
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.shared-sign-dialog :deep(.el-button--primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.shared-sign-dialog :deep(.el-button--success) {
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 600;
  transition: all 0.3s ease;
}

/* 美化取消按钮 */
.shared-sign-dialog :deep(.el-button) {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.shared-sign-dialog :deep(.el-button:hover) {
  border-color: #a8abb2;
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

/* 表单元素美化 */
.shared-sign-dialog :deep(.el-form-item__label) {
  font-weight: 600;
  color: #303133;
}

.shared-sign-dialog :deep(.el-input__inner),
.shared-sign-dialog :deep(.el-textarea__inner) {
  border-radius: 8px;
  border: 1px solid #dcdfe6;
  transition: border-color 0.3s ease;
}

.shared-sign-dialog :deep(.el-input__inner:hover),
.shared-sign-dialog :deep(.el-textarea__inner:hover) {
  border-color: #a8abb2;
}

.shared-sign-dialog :deep(.el-input__inner:focus),
.shared-sign-dialog :deep(.el-textarea__inner:focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 选择框美化 */
.shared-sign-dialog :deep(.el-select .el-input__inner) {
  border-radius: 8px;
}

.shared-sign-dialog :deep(.el-select .el-input__inner:hover) {
  border-color: #a8abb2;
}

.shared-sign-dialog :deep(.el-select .el-input__inner:focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 日期选择器美化 */
.shared-sign-dialog :deep(.el-date-editor.el-input) {
  border-radius: 8px;
}

.shared-sign-dialog :deep(.el-date-editor.el-input:hover) {
  border-color: #a8abb2;
}

.shared-sign-dialog :deep(.el-date-editor.el-input:focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 表格美化 */
.shared-sign-dialog :deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

.shared-sign-dialog :deep(.el-table th) {
  font-weight: 600;
  color: #303133;
}

.shared-sign-dialog :deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 文字按钮美化 */
.shared-sign-dialog :deep(.el-button--text) {
  color: #667eea;
  font-weight: 600;
  padding: 0;
}

.shared-sign-dialog :deep(.el-button--text:hover) {
  color: #764ba2;
  text-decoration: underline;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>